﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.Common;
using System.Data.SqlClient;

namespace AgileFx.MVC.PerformanceTools
{
    public static class LogWriter
    {     
        public static string ConnectionString { get; set; }

        static object _lock = new object();
        static List<LogEntry> entries = new List<LogEntry>();
        static Timer timer = new Timer(TimerEvent, null, 10000, 10000);

        public static void Write(LogEntry entry)
        {
            lock (_lock)
            {
                entries.Add(entry);
            }
        }

        private static void Flush()
        {
            lock (_lock)
            {
                var conn = new SqlConnection(ConnectionString);
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.Transaction = conn.BeginTransaction();

                cmd.CommandText = "INSERT INTO LogEntry (Id, EventId, Type, Date, Time, Ticks, Data, ParentId) VALUES (@pId, @pEventId, @pType, @pDate, @pTime, @pTicks, @pData, @pParentId)";

                var pId = cmd.Parameters.Add("@pId", System.Data.SqlDbType.VarChar, 50);
                var pEventId = cmd.Parameters.Add("@pEventId", System.Data.SqlDbType.VarChar, 50);
                var pType = cmd.Parameters.Add("@pType", System.Data.SqlDbType.VarChar, 50);
                var pDate = cmd.Parameters.Add("@pDate", System.Data.SqlDbType.VarChar, 50);
                var pTime = cmd.Parameters.Add("@pTime", System.Data.SqlDbType.VarChar, 50);
                var pTicks = cmd.Parameters.Add("@pTicks", System.Data.SqlDbType.BigInt);
                var pData = cmd.Parameters.Add("@pData", System.Data.SqlDbType.Text);
                var pParentId = cmd.Parameters.Add("@pParentId", System.Data.SqlDbType.VarChar, 50);

                foreach (var entry in entries)
                {
                    pId.Value = entry.Id;
                    pEventId.Value = entry.EventId;
                    pType.Value = entry.Type;
                    pDate.Value = entry.Date;
                    pTime.Value = entry.Time;
                    pTicks.Value = entry.Ticks;
                    pData.Value = entry.Data;
                    pParentId.Value = entry.ParentId;

                    cmd.ExecuteNonQuery();
                }

                cmd.Transaction.Commit();
                conn.Close();

                entries.Clear();
            }
        }

        public static void TimerEvent(object state)
        {
            Flush();
        }
    }
}